<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{	
	protected $table = 'category';
    protected $primaryKey = 'cate_id';
    public $timestamps = false;
    protected $guarded = [];
    // protected $fillable = ['cate_name', 'cate_title', 'cate_keywords','cate_description','cate_order','cate_id'];

    public function tree()
    {
        $categorys = $this->orderBy('cate_order','asc')->get();
        return $this->getTree($categorys,'cate_name','cate_id','cate_pid');
    }
    
    //栏目名称的二级分类
    public function getTree($data,$field_name,$field_id='id',$field_pid='pid',$pid=0)
    {
    	//先定义一个空数组
        $arr = array();
        //遍历所有数据
        foreach ($data as $k=>$v){
        	//先遍历父类
            if($v->$field_pid==$pid){
                $data[$k]["_".$field_name] = $data[$k][$field_name];
                //将父类赋值到新数组中
                $arr[] = $data[$k];
                //继续遍历出二级子类
                foreach ($data as $m=>$n){
                	//找出子类的pid == 父类的cate_id
                    if($n->$field_pid == $v->$field_id){
                    	//为子类分层
                        $data[$m]["_".$field_name] = '├─ '.$data[$m][$field_name];
                        //将子类赋值到数组中
                        $arr[] = $data[$m];
                    }
                }
            }
        }
        return $arr;
    }
}
